<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
         
        const publisher={
            id:0,
            subscribe:function(channel,fn){
                console.log(this)
            let token='token_'+(this.id++);
            const fnsChannel=this.fns[channel]
            if(fnsChannel){
                fnsChannel[token]=fn;
            }else{
                this.fns[channel]={[token]:fn};
            }
            
            return token
        },
        unSubscribe:function(flag){
            const fns=this.publisher.fns
            if(flag){
                if(typeof flag==='string'){
                    if(flag.findIndex('token')>-1){
                        const obj=fns.values().find(fn=>fn.hasOwnProperty(flag))
                        if(obj){
                            delete obj[flag]
                        }
                    }else{
                        delete fns[flag]
                    }
                }
            }else{
               fns={}
            }
        },
        publish:function(channel,data){
            console.log('发布消息')
            const fns=this.fns
            // 异步执行
            setTimeout(function(){
                if(channel){
                // 如果有传h:频道
                if(fns[channel]){
                    Object.values(fns[channel]).forEach(fn => {
                        fn(data)
                    });
                }
               
                }else{
                    // 没有则通知全部
                    Object.values(fns).forEach(obj => {
                        Object.values(obj).forEach(fn=>{
                            fn(data)
                        });
                    });
                }
            },0)
          
        }, 
        
        fns:{
                // channel:{token:fn}
            }
        }
       
     
 
    
        // 订阅
        publisher.subscribe('pay',function(data){
            console.log('订阅了1',data)
        })
        publisher.subscribe('pay',function(data){
            console.log('订阅了2',data)
        })
        publisher.subscribe('pay',function(data){
            console.log('订阅了3',data)
        })
        publisher.subscribe('pay1',function(data){
            console.log('订阅了1',data)
        })
        publisher.subscribe('pay1',function(data){
            console.log('订阅了2',data)
        })
        publisher.subscribe('pay3',function(data){
            console.log('订阅了3',data)
        })

        console.log(publisher);
        publisher.publish('pay1',{a:'a',b:'b'})
    </script>
</body>
</html>